<?php

/* --------------- Class UserAuthentication 0.1 ------------------
  Class to ease user session based authentication in PHP application.
  Just call this class, initiate the appropriate database, and your
  secure autheticated script just would be running well.

  Created: 5/3/2004 4:03:53 PM
  -------------------------------------------------------- */
define('USER_AUTH', 'USR_AUTH_FMSS.CP_0_0_1');

class UserAuth {

    var $error_string;
    var $table_users;
    var $table_groups;
    var $table_usergroup;
    var $_timeout;
    var $_off_is_called;

    function __init() {
// set this true to enabled time out auo logout remark by @yoog
        $this->_off_is_called = true;
//$this->_off_is_called = false;
        if (!isset($this->_timeout))
            $this->_timeout = 1000;
        if (!isset($this->table_users))
            $this->table_users = "mt_user";
    }

//    function UserAuth() {
//        $this->__init();
//    }
// Main UserAuth function
    function is_logged() {
        try {
            $time_now = time();
            $time = $time_now - $_SESSION[USER_AUTH . 'log_time'] + 10; //10 adalah faktor tambahan ketepatan
            if ($time > $this->_timeout && $this->_off_is_called) {
                $this->error_string = "Your session has been expired after reaching timeout, please login...";
                $this->logout();
            } else {
                $_SESSION[USER_AUTH . 'log_time'] = time();
            }
            $hasil = true;
            if ($_SESSION[USER_AUTH . 'logged'] == USER_AUTH) {
                $hasil = true;
            } else {
                $hasil = false;
            }
            return $hasil;
        } catch (Exception $e) {
            return false;
        }
    }

    function loginproses($username, $password) {
        $CI = & get_instance();
        $modLogin = $CI->load->model('Login_Model');

        //global $dbi;
        $this->__init();
        $is_authenticated = false;

        $data = array('log_time' => date('Y-m-d H:i:s'),
            'log_aktor' => $username,
            'log_event' => 'Login Aplikasi Dari IP ' . $_SERVER['REMOTE_ADDR']
        );


        //$dbi->insert("audit_trail", array("log_time", "log_aktor", "log_event"), array(date("Y-m-d H:i:s"), $username, "Login Aplikasi Dari IP " . $_SERVER["REMOTE_ADDR"]));
        //$row = $dbi->get_row("SELECT id_user, password, nik, id_group_user, is_active FROM " . $this->table_users . " WHERE id_user='" . $username . "' ");
        //$result = $modLogin->login_proses($data, $username);
        $CI = & get_instance();
        $CI->db->insert('audit_trail', $data);
        $result = $CI->db->query("SELECT id_user, password, nik, id_group_user, is_active FROM " . $this->table_users . " WHERE id_user='" . $username . "' ");

        $count = $result->num_rows();

        $is_userexist = false;

        if ($count > 0) {
            $row = $result->row();

            $is_userexist = true;
            $passdb = $row->password;

            if ($password == $passdb) {
                if ($row->is_active) {
                    $is_authenticated = true;
                    $rsNik = $CI->db->query("SELECT k.nama, k.nik FROM mt_karyawan k WHERE k.nik='" . $row->nik . "' ");
                    $row2 = $rsNik->row();
                } else {
                    $this->error_string = "ID Pengguna anda saat ini tidak aktif !";
                }
            } else {
                $this->error_string = "ID Pengguna atau password anda tidak cocok !";
            }
        }

// error handling if doesn't founf
        if (!$is_userexist)
            $this->error_string = "ID Pengguna Belum Terdaftar!";

        if ($is_authenticated) {
//time check
            $userid = $row->id_user;
            $nama = $row2->nama;
            $nik = $row->nik;
            $usergroup = $row->id_group_user;
            $this->setDataSession($userid, $nik, $usergroup, $nama);
            $this->last_login();

            $this->hak_akses_menu();
        }

        return $is_authenticated;
    }

    function setDataSession($userid, $nik, $usergroup, $nama) {
        $_SESSION[USER_AUTH . 'user_id'] = $userid;
        $_SESSION[USER_AUTH . 'nik'] = $nik;
        $_SESSION[USER_AUTH . 'nama'] = $nama;
        $_SESSION[USER_AUTH . 'id_user_group'] = $usergroup;
        $_SESSION[USER_AUTH . 'log_time'] = time();
        $_SESSION[USER_AUTH . 'logged'] = USER_AUTH;
        $_SESSION[USER_AUTH . 'menu'] = $this->setMenu();
    }

    function getUserNIK() {
        try {
            $data = $_SESSION[USER_AUTH . 'nik'];
            return $data;
        } catch (Exception $e) {
            return "";
        }
    }

    function getUserID() {
        try {
            $data = $_SESSION[USER_AUTH . 'user_id'];
            return $data;
        } catch (Exception $e) {
            return "";
        }
    }
    
    function getUserGroup(){
        try {
            $data = $_SESSION[USER_AUTH . 'id_user_group'];
            return $data;
        } catch (Exception $e) {
            return "";
        }
    }

    function getName() {
        return $_SESSION[USER_AUTH . 'nama'];
    }

    function getRole() {
        return $_SESSION[USER_AUTH . 'id_user_group'];
    }

    function last_login() {
        global $dbi, $log, $auth;
        //$dbi->update($this->table_users, array("last_active"), array("" . date("Y-m-d H:i:s") . ""), " id_user='" . $this->getUserID() . "' ");
        $data = array(
            "last_active" => date("Y-m-d H:i:s")
        );

        $where = array(
            "id_user" => $this->getUserID()
        );

        $CI = & get_instance();
        $result = $CI->db->update($this->table_users, $data, $where);
//$dbi->insert("audit_trail", array("log_time", "log_aktor", "log_event"), array(date("Y-m-d H:i:s"), $this->getUserID(), "Login Aplikasi Dari IP ". $_SERVER["REMOTE_ADDR"] ));
    }

    function isApprove($tipe_user_access, $divisi_access) {
        $divisi_access = $this->getRole() == 3 ? $this->getDivisiID() : $divisi_access;
        if ($this->getDivisiID() == $divisi_access && $this->getRole() == $tipe_user_access) {
            return true;
        } else {
            return false;
        }
    }

    function logout($username = '') {
        $_SESSION[USER_AUTH . 'user_id'] = NULL;
        $_SESSION[USER_AUTH . 'user_name'] = NULL;
        $_SESSION[USER_AUTH . 'name'] = NULL;
        $_SESSION[USER_AUTH . 'id_divisi'] = NULL;
        $_SESSION[USER_AUTH . 'divisi'] = NULL;
        $_SESSION[USER_AUTH . 'id_tipe_user'] = NULL;
        $_SESSION[USER_AUTH . 'log_time'] = NULL;
        $_SESSION[USER_AUTH . 'logged'] = NULL;
        $_SESSION[USER_AUTH . 'divisi_nick'] = NULL;
        $_SESSION[USER_AUTH . 'read_granted'] = NULL;
        $_SESSION[USER_AUTH . 'modify_granted'] = NULL;
        $_SESSION[USER_AUTH . 'delete_granted'] = NULL;
        $_SESSION[USER_AUTH . 'last_query'] = NULL;
        $_SESSION[USER_AUTH . 'menu'] = NULL;
        $_SESSION[USER_AUTH . 'nik'] = NULL;
        $_SESSION[USER_AUTH . 'nama'] = NULL;
        $_SESSION[USER_AUTH . 'id_user_group'] = NULL;
        
        $this->_off_is_called = true;
    }

    function session_id() {
        return SID;
    }

    function destroy() {
        session_destroy();
    }

    function set_timeout($sec_timeout) {
        $this->_timeout = $sec_timeout;
    }

    function error($msg = "") {
        if ($msg != "")
            $this->error_string = $msg;

        echo $this->error_string;
        die();
    }

    function getReadAccess($id_menu) {
		if(isset($_SESSION[USER_AUTH . 'read_granted'][$id_menu]) and !empty($_SESSION[USER_AUTH . 'read_granted'][$id_menu]))
			return $_SESSION[USER_AUTH . 'read_granted'][$id_menu];
		else 0;	
    }

    function getModifyAccess($id_menu) {
		if(isset($_SESSION[USER_AUTH . 'modify_granted'][$id_menu]) and !empty($_SESSION[USER_AUTH . 'modify_granted'][$id_menu]))
			return $_SESSION[USER_AUTH . 'modify_granted'][$id_menu];
		else 0;	
    }

    function getDeleteAccess($id_menu) {
		if(isset($_SESSION[USER_AUTH . 'delete_granted'][$id_menu]) and !empty($_SESSION[USER_AUTH . 'delete_granted'][$id_menu]))
			return $_SESSION[USER_AUTH . 'delete_granted'][$id_menu];
		else 0;	
    }

    function hak_akses_menu() 
    {
        $CI = & get_instance();
        
        $rows = $CI->db->query("
            (
                SELECT id_menu, is_read, is_modify, is_delete FROM hak_akses_group WHERE id_group_user = (SELECT id_group_user FROM mt_user WHERE id_user = '" . str_replace('%20', ' ', $this->getUserID()) . "') 
                UNION
                SELECT id_menu, is_read, is_modify, is_delete FROM hak_akses WHERE id_user = '" . str_replace('%20', ' ', $this->getUserID()) . "'
            )
        ");

        $result  = $rows->result();
        $numRows = $rows->num_rows();

        if ($numRows > 0)
        {
            foreach ($result as $data)
            {
                if(!isset($_SESSION[USER_AUTH . 'read_granted'][$data->id_menu]) || ($_SESSION[USER_AUTH . 'read_granted'][$data->id_menu] == 0 || $data->is_read == 1))
                {
                    $_SESSION[USER_AUTH . 'read_granted'][$data->id_menu] = $data->is_read;
                }
                
                if(!isset($_SESSION[USER_AUTH . 'read_granted'][$data->id_menu]) || ($_SESSION[USER_AUTH . 'modify_granted'][$data->id_menu] == 0 || $data->is_modify == 1))
                {
                    $_SESSION[USER_AUTH . 'modify_granted'][$data->id_menu] = $data->is_modify;
                }
                
                if(!isset($_SESSION[USER_AUTH . 'read_granted'][$data->id_menu]) || ($_SESSION[USER_AUTH . 'delete_granted'][$data->id_menu] == 0 || $data->is_delete == 1))
                {
                    $_SESSION[USER_AUTH . 'delete_granted'][$data->id_menu] = $data->is_delete;
                }
            }
        }
    }

    function getActiveMenu() {
        $CI = & get_instance();
        return $result = $CI->db->query("select * from mt_menu where id_menu_induk is NULL AND is_active='1' ORDER BY urutan");
    }

    function getActiveChildMenu($id_menu_induk) {
        $CI = & get_instance();
        return $result = $CI->db->query("select * from mt_menu where id_menu_induk = " . $id_menu_induk . " AND is_active='1' ORDER BY urutan ");
    }

    function getMenu() {
		if(isset($_SESSION[USER_AUTH . 'menu']) and !empty($_SESSION[USER_AUTH . 'menu']))
			return $_SESSION[USER_AUTH . 'menu'];
		else{
			$this->logout();
			redirect('/admin/index', 'refresh');
		}
    }

    function setMenu() {
        $CI = & get_instance();
        $data = array();
        $data['userID'] = $this->getUserID();
        $data['name'] = $this->getName();
        $result = $this->getActiveMenu();
        $data['namamenu'] = array();
        $i = 1;
        foreach ($result->result() as $rowInduk) {
            $data['kodeinduk'][$rowInduk->id_menu] = $rowInduk->id_menu;
            $data['kodeinduk'][$rowInduk->menu] = $rowInduk->menu;
            $data['namamenu'][] = $rowInduk->menu;
            $url = $rowInduk->link;
            $url = str_replace("{root}", base_url(), $url);
            $data['kodeinduk']['link' . $i] = str_replace("{userid}", $data['userID'], $url);
            $rsResult = $this->getActiveChildMenu(trim($data['kodeinduk'][$rowInduk->id_menu]));
            $data['resultMenu'][$rowInduk->menu] = $rsResult->result();
            $data['havechild'][$rowInduk->menu] = $rsResult->num_rows();
            $i++;
        }
        
        $resultpopup = $CI->db->query("select * from mt_menu where is_popup = '1' ORDER BY urutan");
        $data['resultMenu'][1000] = $resultpopup->result();
            
        return $data;
    }

}

?>
